package com.lagou;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义zk工具类
 */
public class ZkUtils {
    //static Logger logger = LoggerFactory.getLogger(ZkUtils.class);

    // 获取连接
    public static ZkClient getCon() {
        ZkClient zkClient = new ZkClient(Const.ZKHOSTS);
        //logger.info("get Connection!!!");
        System.out.println("get Connection!!!");
        return zkClient;
    }

    /**
     * 创建节点和数据
     * @param zkClient zk客户端
     * @param path zk节点路径
     */
    public static void createNode(ZkClient zkClient,String path) {
        // 判断节点是否存在
        boolean exists = zkClient.exists(path);
        String dbConfig = Const.JDBCURL + "\t" + Const.USERNAME + "\t" + Const.PASSWORD;
        //logger.info("dbConfig is " + dbConfig);
        System.out.println("dbConfig is " + dbConfig);

        // 不存在则创建
        if (!exists) {
            // 创建节点并写入数据库连接信息
            zkClient.createPersistent(path);
            zkClient.writeData(path,dbConfig);
            // zkClient.delete(path);
        } else {
            zkClient.writeData(path,dbConfig);
            //logger.info("new dbConfig is " + dbConfig);
            //logger.info("data write successed!!!");
            System.out.println("new dbConfig is " + dbConfig);
            System.out.println("data write successed!!!");
        }

        //logger.info(path + "created!");
        System.out.println(path + "created!");
    }
}
